package com.atguigu.gmall.user.util;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.util.HttpClientUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class BaiDuService {

    private static final Logger log = LoggerFactory.getLogger(BaiDuService.class);

    private static String ak = "EnfvBtgZXLCSEtiawSZf6nDanS84Rpru";


    private static final String URL = "http://api.map.baidu.com/location/ip?ak=" + ak + "&ip=IPaddress";

    private static Map<String, String> map = new HashMap<>();

    static {
        map.put("127.0.0.1", "本机");
        map.put("localhost", "本机");
    }


    public static AreaInfo getArea(String ip) {
        try {
            if (StringUtils.isNotBlank(map.get(ip))) {
                return new AreaInfo(map.get(ip), map.get(ip));
            }
            IpAreaRes res = getAreaFromBaiDu(ip);
            if (null == res) {
                return new AreaInfo();
            }
            String province = res.getContent().getAddress_detail().getProvince();
            String city = res.getContent().getAddress_detail().getCity();
            return new AreaInfo(province, city);
        } catch (Exception e) {
            log.error("[用户服务],调用百度地图获取城市异常:{}", e);
            return null;
        }
    }

    private static IpAreaRes getAreaFromBaiDu(String ip) {
        String url = StringUtils.replace(URL, "IPaddress", ip);
        String response = null;
        log.info("请求百度获取ip地址所属地区,url:{}", url);
        try {
            response = HttpClientUtil.doGet(url);
        } catch (Exception e) {
            log.error("请求百度获取ip地址所属地区异常:" + e.getMessage(), e);
        }
        if (StringUtils.isBlank(response)) {
            log.error("请求百度获取ip地址所属地区异常,返回为空");
            return null;
        }
        IpAreaRes res = JSON.parseObject(response, IpAreaRes.class);
        if (0 != res.getStatus()) {
            log.error("请求百度根据ip获取地区信息失败，状态码：{}", res.getStatus());
            return null;
        }

        return res;

    }

    public static void main(String[] args) {
        //BaiDuService baiduService = new BaiDuService();
        String ip = "61.50.127.14";
        AreaInfo res = BaiDuService.getArea(ip);
        System.err.println(res.getCity());

    }

}
